package xyz.xiaomeiqiu.netty.support;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpHandler extends ChannelInboundHandlerAdapter {

    private final Logger Logger = LoggerFactory.getLogger(getClass());

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            FullHttpRequest httpRequest = (FullHttpRequest) msg;
            String uri = httpRequest.uri();
            if(uri.contains("/test")){
                String result = HttpClientUtils.sendGet("https://www.baidu.com");
                handlerRequest(httpRequest, ctx, result, "text/html");
            } else {
                handlerRequest(httpRequest, ctx, "请求"+uri+"已收到", null);
            }
        } catch (Exception e){
            Logger.error("inbound 发生异常", e);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    private void handlerRequest(FullHttpRequest httpRequest, ChannelHandlerContext ctx, String responseMsg, CharSequence contentType) {
        FullHttpResponse httpResponse = null;
        try {
            byte[] bytes = responseMsg.getBytes("UTF-8");
            httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(bytes));
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType==null?HttpHeaderValues.APPLICATION_JSON:contentType);
            httpResponse.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, bytes.length);

        } catch (Exception e) {
            Logger.error("处理http response 发生错误", e);
            httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT);
        } finally {
            if(httpResponse != null){
                if(!HttpUtil.isKeepAlive(httpRequest)){
                    ctx.write(httpResponse).addListener(ChannelFutureListener.CLOSE);
                } else {
                    httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                    ctx.write(httpResponse);
                }
            }
        }
    }
}
